package web.tcp.test1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description
 * @className TestServer
 * @package web.tcp.test1
 * @author dongww@hsyuntai.com
 * @date 2020/3/11 14:44
 * @copyright 版权归 HSYUNTAI 所有
 */
public class TestServer {

    InputStreamReader isr;
    BufferedReader br;
    PrintWriter pw;


    public static void main(String[] args) {
        TestServer ts = new TestServer();

    }

    public TestServer() {

        try {
            //监听某个端口
            ServerSocket ss = new ServerSocket(9999);
            System.out.println("我是socket服务器正在监听9999端口.........");
            //等待某个客户端来连接，accept()函数将返回一个socket连接
            Socket s = ss.accept();

            //要读取s中传递的数据
            isr = new InputStreamReader(s.getInputStream());
            br = new BufferedReader(isr);
            //通过readline()函数来读写数据
            String info = br.readLine();
            System.out.println("服务器收到的消息为：" + info);

            //我们通过pw向s写数据,true表示即时刷新
            pw = new PrintWriter(s.getOutputStream(), true);
            pw.println("你也好，我是服务器！！！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }

                if (br != null) {
                    br.close();
                }

                if (isr != null) {
                    isr.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}